<script setup>
  import {
    getCategoryList,
    getBookList,
    getBookCopyList,
    addBookCopy,
    deleteBookCopy,
    getbookShelfTree,
    addBook,
  } from '@/api'
  import { ElMessageBox } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { ref, onMounted, useTemplateRef } from 'vue'
  import { useDynamicForm } from '@/hooks'

  const { openForm } = useDynamicForm()
  const categoryList = ref([])
  const bookList = ref([])
  const searchText = ref('')
  const categoryId = ref('')
  const form = useTemplateRef('form')
  const bookShelfTree = ref([])

  const bookCopyTableColumns = [
    { label: 'Id', prop: 'id' },
    { label: '状态', prop: 'bookCopyStatus', filter: val => (val ? '借出' : '在馆') },
    { label: '操作', prop: 'option' },
  ]
  const bookTableColumns = [
    { label: 'Id', prop: 'id' },
    { label: '书名', prop: 'title' },
    { label: '作者', prop: 'author' },
    { label: '出版社', prop: 'publisher' },
    { label: '售价', prop: 'price' },
    { label: '分类', prop: 'categoryId', filter: val => categoryList.value.find(item => item.value === val)?.label },
    { label: '存放位置', prop: 'fullLocationPath', width: 300 },
    { label: '操作', prop: 'option' },
  ]

  const handleGetCategoryList = () => {
    getCategoryList().then(res => {
      categoryList.value = res.data.map(item => ({ value: item.id, label: item.name }))
    })
  }

  const handleSearchBook = () => {
    const title = searchText.value || undefined
    const id = categoryId.value || undefined
    const p = getBookList({ title, categoryId: id }).then(res => {
      bookList.value = res.data.map(item => ({ ...item, bookCopies: [], got: false }))
    })

    form.value.load(p)
  }

  const handleGetBookCopies = (row, foucs = false) => {
    if (row.got && !foucs) return

    getBookCopyList(row.id).then(res => {
      const idx = bookList.value.findIndex(item => item.id === row.id)
      bookList.value[idx].got = true
      bookList.value[idx].bookCopies = res.data.map(({ id, bookCopyStatus }) => ({ id, bookCopyStatus }))
    })
  }

  const onChangeCategory = () => {
    handleSearchBook()
  }

  const onExpandChange = row => {
    handleGetBookCopies(row)
  }

  const onAddBookCopy = row => {
    ElMessageBox.confirm('确认新增副本？', '提示').then(() => {
      addBookCopy({ bookId: row.id }).then(() => {
        ElMessage.success('新增副本成功')
        handleGetBookCopies(row, true)
      })
    })
  }

  const onDeleteBookCopy = (row, bookRow) => {
    console.log(row)

    ElMessageBox.confirm('确认删除该副本？', '提示').then(() => {
      deleteBookCopy({ id: row.id }).then(() => {
        ElMessage.success('删除成功')
        handleGetBookCopies(bookRow, true)
      })
    })
  }

  const onClickAddBook = () => {
    const options = {
      title: '新增图书',
      fields: [
        { label: '书名', key: 'title' },
        { label: '作者', key: 'author' },
        { label: '出版社', key: 'publisher' },
        { label: '售价', key: 'price', type: 'number', default: 0, min: 0 },
        { label: '分类', key: 'categoryId', type: 'select', options: categoryList.value },
        {
          label: '书架位置',
          key: 'bookshelfId',
          type: 'cascader',
          options: bookShelfTree.value,
          onChange: val => {
            if (!val || val.length < 3) {
              // 没选到第三级，清空或提示
              ElMessage.warning('请选择完整的三级分类')
              return
            }
            // val 就是 [libId, floorId, classroomId]
            const classroomId = val[2]
          },
        },
      ],
      onConfirm: (data, { close, setLoading }) => {
        if (data.bookshelfId.length !== 3) {
          ElMessage.warning('请选择完整的三级分类')
          return
        }

        setLoading(true)
        addBook({ ...data, bookshelfId: data.bookshelfId[2] })
          .then(() => {
            ElMessage.success('新增图书成功')
            handleSearchBook()
            close()
          })
          .finally(() => setLoading(false))
      },
    }

    options.fields = options.fields.map(field => ({ ...field, required: true }))

    openForm(options)
  }

  const handleGetBookShelf = () => {
    getbookShelfTree().then(res => {
      const map = val => {
        val.forEach(item => {
          item.label = item.name
          item.value = item.id

          if (item.children) map(item.children)
        })
      }
      map(res.data)
      bookShelfTree.value = res.data
    })
  }

  onMounted(() => {
    handleGetCategoryList()
    handleSearchBook()
    handleGetBookShelf()
  })
</script>

<template>
  <page-layout>
    <template #header>
      <el-input
        v-model="searchText"
        placeholder="请输入书名或作者"
        style="width: 200px"
        clearable
        @blur="handleSearchBook"
      />
      <el-select
        v-model="categoryId"
        placeholder="选择图书分类"
        style="width: 200px"
        @change="onChangeCategory"
        clearable
      >
        <el-option v-for="item in categoryList" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-button icon="Search" @click="onChangeCategory">搜索</el-button>
      <el-button type="success" @click="onClickAddBook">新增图书</el-button>
    </template>

    <dynamic-table :data="bookList" :columns="bookTableColumns" ref="form" @expand-change="onExpandChange" row-key="id">
      <template #option="{ row }">
        <el-button type="success" @click="onAddBookCopy(row)">新增副本</el-button>
      </template>
      <el-table-column type="expand" label="副本" width="100">
        <template #default="{ row }">
          <dynamic-table :columns="bookCopyTableColumns" :data="row.bookCopies">
            <template #option="{ row: r }">
              <el-button type="danger" :disabled="r.bookCopyStatus !== 0" @click="onDeleteBookCopy(r, row)">
                删除
              </el-button>
            </template>
          </dynamic-table>
        </template>
      </el-table-column>
    </dynamic-table>
  </page-layout>
</template>

<style scoped lang="less"></style>
